package org.aclyyx.malata.app.log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.aclyyx.malata.app.StaticData;

public class Logger {

	public static String logFile = "";
	
	public static void log(String msg) {
		try {
			pDir();
			getLogFileName();
			writeLog(msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private static void pDir() {
		File file = new File(StaticData.LOG_FILE_PATH);
		if (!file.exists() || file.isFile()) {
			file.mkdir();
		}
	}
	
	private static void getLogFileName() throws IOException {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
		if (logFile.equals("")) {
			logFile = StaticData.LOG_FILE_PATH + StaticData.SP + format.format(new Date()) + ".txt";
	
			File file = new File(logFile);
			if (!file.exists() || file.isDirectory()) {
				file.createNewFile();
			}
		}
	}
	
	private static void writeLog(String msg) throws IOException {
		File file = new File(logFile);
		BufferedReader br = new BufferedReader(new FileReader(file));
		String temp = br.readLine();
		StringBuffer ws = new StringBuffer();
		while (temp != null) {
			ws.append(temp).append("\r\n");
			temp = br.readLine();
		}
		br.close();
		
		BufferedWriter bw = new BufferedWriter(new FileWriter(file));
		bw.write(ws.toString());
		if (msg != null) {
			bw.write(msg);
		}
		bw.close();
	}
	
	public static void main(String[] ss) {
		Logger.log("hi,aclyyx!1");
		Logger.log("hi,aclyyx!2");
		Logger.log("hi,aclyyx!3");
		Logger.log("hi,aclyyx!4");
		Logger.log("hi,aclyyx!5");
	}
}
